/*jslint browser: true*/
/*global $, jQuery, alert, window*/

/*实现python中str的format方法”*/
String.prototype.format = function (replace_dict) {
    "use strict";
    var result = this,
        key,
        value,
        reg,
        index;
    for (key in replace_dict) {
        if (replace_dict.hasOwnProperty(key)) {
            value = replace_dict[key];
            reg = new RegExp("({" + key + "})", "g");
            result = result.replace(reg, value);
        }
    }
    return result;
};

/*按照format_dict，转换server端得到的数据*/
function fetchData(data_list, format_dict) {
    "use strict";
    /*window.debug_data = {
        data_list: data_list,
        format_dict: format_dict
    }*/
    var return_list = [],
        tempDict = {},
        tempData,
        index,
        length = data_list.length,
        server_var_name,
        js_ver_name;
    for (index = 0; index < length; index = index + 1) {
        tempDict = {};
        tempData = data_list[index];
        for (server_var_name in format_dict) {
            if (format_dict.hasOwnProperty(server_var_name) &&
                    tempData.hasOwnProperty(server_var_name)) {
                js_ver_name = format_dict[server_var_name];
                tempDict[js_ver_name] = tempData[server_var_name];
            }
        }
        return_list.push(tempDict);
    }
    return return_list;
}
function fetchBack(data_list, format_dict) {
    "use strict";
    var return_list = [],
        tempDict = {},
        tempData,
        index,
        length = data_list.length,
        server_var_name,
        js_ver_name;
    for (index = 0; index < length; index = index + 1) {
        tempDict = {};
        tempData = data_list[index];
        for (server_var_name in format_dict) {
            if (format_dict.hasOwnProperty(server_var_name)) {
                js_ver_name = format_dict[server_var_name];
                if (tempData.hasOwnProperty(js_ver_name)) {
                    tempDict[server_var_name] = tempData[js_ver_name];
                }
            }
        }
        return_list.push(tempDict);
    }
    return return_list;
}

window.format = {
    "char" : {  "char_id": "id",
                "char_major_id": "major_id",
                "char_name": "name",
                "char_father_id": "father_id",
                "char_is_kp": "is_kp",
                "char_listorder": "listorder",
                "is_test": "is_test" },
    "question": {
        "main_id": "id",
        "hat_id": "hat_id",
        "sub_num": "sub_num",
        "main_creater_id": "creater_id",
        "main_major_id": "major_id",
        "main_timestamp": "timestamp",
        "main_char_id_list": "char_id_list",
        "main_category_num": "category_num",
        "main_level_num": "level_num",
        "main_description": "description"
    },
    "hat": {
        "hat_id": "id",
        "hat_image_id": "hat_image_id",
        "hat_body_text": "hat_body"
    },
    "sub": {
        "sub_id": "id",
        "sub_image_id": "image_id",
        "sub_options_count": "options_count",
        "sub_answer": "answer",
        "sub_analysis": "analysis",
        "sub_body": "body",
        "sub_tip": "tip",
        "sub_options": "options"
    },
    "major": {  "major_id" : "id",
                "major_name" : "name"},
    "author": { "user_id" : "id",
                "user_fullname": "name"},
    "paper" : { "paper_id": "id",
                "paper_detail_id": "detail_id",
                "paper_major_id": "major_id",
                "paper_author_id": "creater_id",
                "paper_category": "category_num",
                "paper_timestamp": "timestamp",
                "paper_time_limit": "time_limit",
                "paper_score": "score",
                "paper_pass_score": "pass_score",
                "paper_name": "name",
                "paper_is_active": "is_active",
                "count_A1": "count_A1",
                "count_A2": "count_A2",
                "count_B1": "count_B1",
                "count_A3": "count_A3",
                "count_A4": "count_A4",
                "choice_A1": "choice_A1",
                "choice_A2":  "choice_A2",
                "choice_B1": "choice_B1",
                "choice_A3": "choice_A3",
                "choice_A4": "choice_A4",
                "score_A1": "score_A1",
                "score_A2": "score_A2",
                "score_B1": "score_B1",
                "score_A3": "score_A3",
                "score_A4": "score_A4",
                "id_list_A1": "id_list_A1",
                "id_list_A2": "id_list_A2",
                "id_list_B1": "id_list_B1",
                "id_list_A3": "id_list_A3",
                "id_list_A4": "id_list_A4"
              },
    "detail": {
        "detail_id": "id",
        "detail_hat": "hat",
        "detail_question": "question",
        "detail_answer": "answer"
    },
    "exam": {
        "exam_id": "id",
        "exam_author_id": "user_id",
        "exam_author_search": "creater_id",
        "exam_detail_id": "detail_id",
        "exam_paper_id": "paper_id",
        "exam_category": "category_num",
        "exam_start_time": "start_time",
        "exam_time_limit": "time_limit",
        "exam_end_time": "end_time",
        "exam_date_num": "date",
        "exam_score": "score",
        "exam_name": "name",
        "exam_answer": "answer"
    }
};
window.format.s2c = fetchData;
window.format.c2s = fetchBack;

/**=======================================
=========================================
=========================================*/
function getCategoryByNum(num_value) {
    "use strict";
    var index = parseInt(num_value, 10);
    return window.category_list[index - 1];
}
function getCategoryNum(value_str) {
    "use strict";
    var category_list = window.category_list,
        index,
        length = category_list.length;
    for (index = 0; index < length; index = index + 1) {
        if (value_str === category_list[index]) {
            return index + 1;
        }
    }
    return 0;
}
window.category_list = ["A1", "A2", "B1", "A3", "A4"];
window.desp_dict = {
    "A1": "A1型题（单句型最佳选择题)：每道试题由1个题干和5个供选择的备选答案组成。题干以叙述式单句出现，备选答案中只有1个是最佳选择，称为正确答案，其余4个均为干扰答案。 干扰答案或是完全不正确，或是部分正确。",
    "A2": "A2型题（病例摘要型最佳选择题)：试题结构是由1个简要病历作为题干、5个供选择的备选答案组成，备选答案中只有1个是最佳选择。",
    "B1": "B1型题（标准配伍题)：试题开始是5个备选答案，备选答案后提出至少2道试题， 要求应试者为每一道试题选择一个与其关系密切的答案。 在一组试题中，每个备选答案可以选用一次，也可以选用数次，但也可以一次不选用。",
    "A3": "A3型题（病例组型最佳选择题)：试题结构是开始叙述一个以患者为中心的临床情景，然后提出2个～3个相关问题， 每个问题均与开始的临床情景有关，但测试要点不同，且问题之间相互独立。",
    "A4": "A4型题（病例串型最佳选择题)：开始叙述一个以单一病人或家庭为中心的临床情景，然后提出3个～6个相关问题。 当病情逐渐展开时，可以逐步增加新的信息。有时陈述了一些次要的或有前提的假设信息， 这些信息与病例中叙述的具体病人并不一定有联系。 提供信息的顺序对回答问题是非常重要的。每个问题均与开始的临床情景有关，又与随后的改变有关。"
};
window.category_list.getNameByNum = getCategoryByNum;
window.category_list.getNumByName = getCategoryNum;

/**=======================================
=========================================
=========================================*/
function getLevelByNum(num_value) {
    "use strict";
    var index = parseInt(num_value, 10);
    return window.level_list[index - 1];
}
function getLevelNum(value_str) {
    "use strict";
    var level_list = window.level_list,
        index,
        length = level_list.length;
    for (index = 0; index < length; index = index + 1) {
        if (value_str === level_list[index]) {
            return index + 1;
        }
    }
    return 0;
}
window.level_list = ["易", "中", "难"];
window.level_list.getNameByNum = getLevelByNum;
window.level_list.getNumByName = getLevelNum;

/**=======================================
=========================================
=========================================*/
if (!window.sessionStorage.getItem("pythonems")) {
    window.localStorage.setItem("pythonems", "false");
}
window.onstorage = function (event) {
    "use strict";
    if (event.key === "pythonems" && event.newValue === "false") {
        window.localStorage.setItem("pythonems", "true");
        //console.log("onstorage: true")
    }
};
window.storage = function (list_key, data_list) {
    "use strict";
    var self_win = window,
        saved_data;
    if (data_list) {
        self_win.localStorage.removeItem(list_key);
        self_win.localStorage.setItem(list_key, JSON.stringify(data_list));
    } else {
        saved_data = JSON.parse(self_win.localStorage.getItem(list_key));
        if (!saved_data) {
            $.ajax({
                url:  list_key,
                type: "GET",
                dataType: "json",
                async: false,
                success: function (result, status) {
                    saved_data = result.data;
                    self_win.localStorage.setItem(list_key, JSON.stringify(result.data));
                }
            });
        }
        return saved_data;
    }
};
window.storageRemove = function (list_key) {
    "use strict";
    window.localStorage.removeItem(list_key);
};
function deleteFromStorag(key, format, remove_id) {
    "use strict";
    var saved_list = window.storage(key),
        transed_list = window.fetchData(saved_list, format),
        index = 0,
        length = transed_list.length,
        item;
    remove_id = parseInt(remove_id, 10);
    for (index = 0; index < length; index = index + 1) {
        item = transed_list[index];
        if (item.id === remove_id) {
            saved_list.splice(index, 1);
            break;
        }
    }
    window.storage(key, saved_list);
}

/**csrf token*/
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
    "use strict";
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        "use strict";
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});